﻿using System.Data.SqlClient;
using BookManage.BLL;
using BookManage.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BookManage;

namespace BookManage
{
    public partial class frmBorrow : Form
    {
       /* static int i = 1;
        static int BorrowID;*/
        private DataTable dt = null;//存放查询结果，并给DataGridView drvReader提供数据
        //private DataTable dm = null;
        private BorrowAdmin borrowBLL = new BorrowAdmin();
        public static Reader reader = new Reader();
        public static Borrow borrow = new Borrow();
        public static Book book = new Book();
        private opStatus ops;//枚举类型，表示3种窗体的状态—查询、借阅
        public frmBorrow()
        {
            InitializeComponent();
        }
        //dgvBook窗口，显示书籍信息
        private void SetStatus(opStatus opst)
        {
            ops = opst;
            switch (ops)
            {
                case opStatus.inOther:
                    groupBox1.Enabled = true;  //查询，续借，还书，缴纳等
                    btnBorrow.Enabled = true;
                    break;
                case opStatus.inBorrow:
                    groupBox1.Enabled = false;  //查询结果
                    btnBorrow.Enabled = true;
                    break;
            }
        }

        private void ShowBookData()
        {
           dgvBook.DataSource = dt;
            foreach (DataColumn dc in dt.Columns)
            {
                dgvBook.Columns[dc.ColumnName].HeaderText = Book.ColumnTitle(dc.ColumnName);
            }
        }
        //dgvBorrow窗口，显示借阅信息
        private void ShowBorrowData()
        {
            dgvBorrow.DataSource = dt;
            foreach (DataColumn dc in dt.Columns)
            {
                dgvBorrow.Columns[dc.ColumnName].HeaderText = Borrow.ColumnTitle(dc.ColumnName);
            }
        }
        private void SelectRd_Click(object sender, EventArgs e)
        {
            SetStatus(opStatus.inOther);
            int rdID;
            if (txtrdID.Text.Trim() == "")
            {
                MessageBox.Show("读者证号不能为空");
                rdID = 0;
            }
            else
            {
                int i = txtrdID.Text.IndexOf("--");
                if (i > 0)
                {
                    rdID = Convert.ToInt32(txtrdID.Text.Substring(0, i));
                }
                else
                {
                    rdID = Convert.ToInt32(txtrdID.Text);
                }
            }
            dt = borrowBLL.GetBorrow(rdID);
            ShowBorrowData();
        }

        private void SelectBk_Click(object sender, EventArgs e)
        {
            SetStatus(opStatus.inOther);
            int bkID;
            string bkName;
            if (txtbkCode.Text.Trim() == "")
            {
                bkID = 0;
            }
            else
            {
                int i = txtbkCode.Text.IndexOf("--");
                if (i > 0)
                {
                    bkID = Convert.ToInt32(txtbkCode.Text.Substring(0, i));
                }
                else
                {
                    bkID = Convert.ToInt32(txtbkCode.Text);
                }
            }
            bkName = txtbkName.Text;
            dt = borrowBLL.GetBook(bkID,bkName);
            ShowBookData();
        }
        int  borrowID;
        private void SetBorrowToText()
        {
            txtrdID.Text = Convert.ToString(borrow.rdID);
            txtbkCode.Text = Convert.ToString(borrow.bkID);
            txtPay.Text = Convert.ToString(borrow.IdOverMoney);
            borrowID = borrow.BorrowID;
        }
        private void SetBookToText()
        {
            txtbkCode.Text = Convert.ToString(book.bkID);
            txtbkName.Text = book.bkName;
        }
        private void dgvBorrow_SelectionChange(object sender, EventArgs e)
        {
            if (dgvBorrow.CurrentCell == null)
                return;
            borrow = BorrowAdmin.GetBorrowByBrwID(Convert.ToInt32(dgvBorrow["borrowID", dgvBorrow.CurrentCell.RowIndex].Value.ToString()));
            SetBorrowToText();

        }
        private void dgvBook_SelectionChange(object sender, EventArgs e)
        {
            if (dgvBook.CurrentCell == null)
                return;
            book = BookAdmin.GetBook(Convert.ToInt32(dgvBook["bkID", dgvBook.CurrentCell.RowIndex].Value.ToString()));
            SetBookToText();
        }

        private void btnBorrow_Click(object sender, EventArgs e)
        {
            /*
            1）、先看读者证状态是否有效，通过借书证号从 TB_Reader 表获取状态；
            2）、判断书籍状态，是否在馆
            3）、读书证有效，书籍在馆，再看读者借书数量是否超过最大借书数量，先从Reader 表获取读者类别，再从TB_ReaderType 表最多可借数量
            4）、最后看读者是否有图书超期未归还，若有，需要先交清罚款才能借书
            */
            /*int rdID, CanLendQty, rdBorrowQty, CanLendDay;
            int rdType;
            Reader RT = new Reader();
            string rdStatus,bkStatus;

            DataRow ds = null;
            DataRow dr = null;

            //逐渐遍历 dgvBook 窗口的每一行，即书籍信息
             for (int i = 0; i < dgvBook.SelectedRows.Count; i++)
             {
                 dr = (dgvBook.SelectedRows[i].DataBoundItem as DataRowView).Row;
             }
            //逐渐遍历dgvReader窗口的每一行，即读者信息
            for (int j=0;j<dgvReader.SelectedRows.Count;j++)
            {
                ds = (dgvReader.SelectedRows[j].DataBoundItem as DataRowView).Row;
            }
            
            /*
            rdType需要初始化，通过一个数组来获取该行的值，rdType是数组第四个元素（TB_Reader)
            这里是利用DataTable类型的变量来存放查询结果，再通过变量取值
            也可以定义一个Reader类型对象rdType，rdType=borrow.GetReaderType(rdID)
            */
            // rdType = Convert.ToInt32(ds.ItemArray[3]);

            /*  dm = borrowBLL.GetrdStatus(rdID);
              rdStatus = Convert.ToString(dm.Rows[0][0]);//读书证状态，第一行第一列
              rdBorrowQty = Convert.ToInt32(dm.Rows[0][1]);*/

            /*dt = borrowBLL.GetReaderType(rdType);
            CanLendQty = Convert.ToInt32(dt.Rows[0][0]);//可借书数量，第一行第一列
            CanLendDay = Convert.ToInt32(dt.Rows[0][1]);//可借书天数，第一行第二列*/
            //bkStatus = Convert.ToString(dr.ItemArray[15]);//通过一个数组来获取该行的值，bkStatus是数组第十六个元素（TB_Book)
            SetStatus(opStatus.inBorrow);


            if (txtbkCode.Text.Trim() == "" || txtrdID.Text.Trim() == "")
                MessageBox.Show("请输入书号或书名！");
            else
            {
                int rdID = Convert.ToInt32(txtrdID.Text.Trim());//初始化
                reader = ReaderAdmin.GetReader(rdID);
                string rdStatus = reader.rdStatus;

                int rdType = reader.rdType;
                int rdBorrowQty = reader.rdBorrowQty;
                ReaderType readertype = ReaderTypeAdmin.GetReaderType(rdType);
                int CanLendQty = readertype.CanLendQty;
                int CanLendDay = readertype.CanLendDay;

                if (rdStatus != "有效")
                    MessageBox.Show("借书证无效，无法借书！！！");
                
                else
                {
                    int bkID = Convert.ToInt32(txtbkCode.Text.Trim());
                    //string bkCode = txtbkCode.Text;
                    int IsFind = BookAdmin.IsFindBook(bkID);
                    if (IsFind == 0)
                        MessageBox.Show("对不起，图书馆没有该书！！！");
                    else
                    {
                        book = BookAdmin.GetBook(bkID);//根据bkID获取Book对象
                        //book = BookAdmin.GetBookByBkCode(bkCode);
                        string bkStatus = book.bkStatus;//根据Book对象获取书状态
                        if (bkStatus != "在馆")
                        {
                            MessageBox.Show("对不起，该书不在馆！！！");
                        }
                        else
                        {
                            if (rdBorrowQty >= CanLendQty)
                            {
                                MessageBox.Show("已借书数超出最大可借书量，无法借书！！！");
                            }
                            else
                            {
                                Reader rd = frmLogin.reader;
                                if (borrow.BorrowID == 0)
                                {
                                    borrow.BorrowID = borrow.BorrowID + 1;
                                }
                                else
                                {
                                    dt = BorrowAdmin.GetLastBrwID();
                                    string BorrowID = dt.Rows[0]["BorrowID"].ToString();
                                    borrow.BorrowID = Convert.ToInt32(BorrowID) + 1;
                                    //MessageBox.Show(Convert.ToString(borrow.BorrowID));
                                }
                                borrow.rdID = rdID;
                                borrow.bkID = book.bkID;
                                borrow.IdContinueTimes = 0;
                                borrow.IdDateOut = DateTime.Now;//设置结束日期为系统当前时间
                                borrow.IdDateRetPlan = DateTime.Now.AddDays(CanLendDay);//还书时间为当前日期+可借书日期
                                                                                        // borrow.IdDateRetAct = DateTime.MaxValue;//不确定还书时间，设为最大时间
                                borrow.IdDateRetAct = DateTime.Now;
                                borrow.IdOverDay = 0;
                                borrow.IdOverMoney = 0;
                                borrow.IdPunishMoney = 0;
                                borrow.IsHasReturn = false;
                                borrow.OperatorLend = rd.rdName;
                                borrow.OperatorRet = rd.rdName;
                                borrowBLL.Add(borrow); //插入借阅记录
                                borrowBLL.UpdateBook(borrow);//更新图书
                                reader.rdID = rdID;
                                borrowBLL.UpdateReader(reader);//更新读者借书数量

                                dt = borrowBLL.GetBorrow(rdID);
                                ShowBorrowData();
                                MessageBox.Show("借书成功！！！");
                            }
                        }
                    }
                }
            }
        }
        private void btnRenew_Click(object sender, EventArgs e)
        {
            SetStatus(opStatus.inOther);
            int rdID = Convert.ToInt32(txtrdID.Text);//初始化
            reader = ReaderAdmin.GetReader(rdID);//根据rdID获取Reader对象
            string rdStatus = reader.rdStatus;

            int rdType = reader.rdType;//根据Reader对象获取读者类别
            ReaderType readertype = ReaderTypeAdmin.GetReaderType(rdType);//根据ReaderType获取读者类别对象
            int CanLendDay = readertype.CanLendDay;//由ReaderT对象获取可借书天数，判断有没有超期
            int CanContinueTimes = readertype.CanContinueTimes;////由ReaderType对象获取可续借次数

            int bkID= Convert.ToInt32(txtbkCode.Text);//初始化
                                                    //borrow = BorrowAdmin.GetAllBorrow(rdID,bkID);
           // MessageBox.Show(Convert.ToString(borrowID));
            borrow = BorrowAdmin.GetBorrowByBrwID(borrowID);
           
            int IdContinueTimes = borrow.IdContinueTimes;
            //int BorrowID = borrow.BorrowID; 

            //先根据续借次数判断是否可续借
            if (IdContinueTimes >= CanContinueTimes)
            {
                MessageBox.Show("对不起，您的续借次数已超出最大可续借次数！！！");

            }
            else
            {
                borrow.BorrowID = borrow.BorrowID;
                borrow.IdContinueTimes = IdContinueTimes;
                borrow.IdDateOut = DateTime.Now;
                //borrow.IdDateRetPlan = DateTime.Now.AddDays(CanLendDay);
                borrow.IdDateRetPlan = borrow.IdDateRetPlan.AddDays(CanLendDay);
                borrowBLL.UpdateContinue(borrow);

                dt = borrowBLL.GetBorrow(rdID);
                ShowBorrowData();
                MessageBox.Show("续借成功！！！");
            }
        }
        private void btnLend_Click(object sender, EventArgs e)
        {
            SetStatus(opStatus.inOther);
            /*
            先根据书从 Borrow表 找到借阅信息(rdID,bkID)
            判断读者类别
            判断超期：1）、IdDateRetAct > IdDateRetPlan，IdDateRetPlan=IdDateOut+CanLendDay
                       2)、IdDateRetAct- IdDateOut > CanLendDay
            超期不能还书，先交清罚款 IdOverMoney=IdOverDay * 0.05
            */
            
            if (txtbkCode.Text == "")
                MessageBox.Show("请输入书号！！！");
            else
            {
                Borrow borrow = new Borrow();
                int bkID = Convert.ToInt32(txtbkCode.Text);//初始化

                //borrow = BorrowAdmin.GetBorrowByBkID(bkID);
                borrow = BorrowAdmin.GetBorrowByBrwID(borrowID);

                borrow.IdDateRetAct = DateTime.Now;//还书日期
                                                   /* MessageBox.Show("还书日期"+Convert.ToString(borrow.IdDateRetAct));
                                                    MessageBox.Show("应还日期"+Convert.ToString(borrow.IdDateRetPlan));*/
                if (Convert.ToInt32(borrow.IsHasReturn) != 0)
                    MessageBox.Show("该图书已归还！！！");
                else if (DateTime.Compare(borrow.IdDateRetAct, borrow.IdDateRetPlan) > 0)
                {
                    DateTime d1 = borrow.IdDateRetAct; //实际还书日期
                    DateTime d2 = borrow.IdDateRetPlan; //应还日期
                    System.TimeSpan d3 = d1 - d2;
                    float IdOverDay = d3.Days;
                    float IdOverMoney = Convert.ToSingle((float)(IdOverDay) * 0.05);
                    int BorrowID = borrow.BorrowID;
                    BorrowAdmin.UpdateBrwByPunish(BorrowID, IdOverDay, IdOverMoney);
                    MessageBox.Show("图书超期，请先交清罚款！罚款金额为： " + IdOverMoney);
                }
                else
                {
                    int BorrowID = borrow.BorrowID;
                    borrow.BorrowID = BorrowID;
                    //BorrowAdmin.DeleteBorrow(borrow);
                    BorrowAdmin.UpdateBrwByLend(borrow);//还书更新Borrow表，已还书，超期清0
                    BorrowAdmin.UpdateBookByLend(borrow); //还书更新Book表，图书在馆，数量+1
                    BorrowAdmin.UpdateReaderByLend(borrow);
                    dt = borrowBLL.GetBorrow(borrow.rdID);
                    ShowBorrowData();
                    MessageBox.Show("还书成功！！！");
                }
            }
        }
        private void btnBack_Click(object sender, EventArgs e)
        {
        //    SetStatus(opStatus.inOther);
            this.Close();
        }

        private void btnPayPunish_Click(object sender, EventArgs e)
        {
            SetStatus(opStatus.inOther);
            int rdID = Convert.ToInt32(txtrdID.Text);
            int bkID = Convert.ToInt32(txtbkCode.Text);
            DateTime IdDateRetPlan = DateTime.Now.AddDays(1);
            if (txtrdID.Text == "" || txtbkCode.Text == "" || txtPay.Text == "")
                MessageBox.Show("缴纳罚款请输入读者号和书号！！！");
            else
            {
                float IdPunishMoney = Convert.ToSingle(txtPay.Text);
                borrow = BorrowAdmin.GetAllBorrow(rdID, bkID);
                if (borrow.IdOverMoney == 0)
                    MessageBox.Show("您没有超期记录，不需要还款！！！");
                else if (borrow.IdOverMoney != IdPunishMoney)
                {
                    MessageBox.Show("您缴纳的金额小于应缴纳金额，请一次交清完毕！！！");
                    MessageBox.Show("您的应罚款金额为：  " + borrow.IdOverMoney);
                }
                else
                {
                    //缴纳后IdPunishMoney为缴纳的金额；IdDateRetPlan：应在今天之内归还；应缴纳金额更新为0
                    BorrowAdmin.UpdatePunish(rdID, bkID, IdPunishMoney, IdDateRetPlan);
                    MessageBox.Show("已缴清应罚金额！务必在今天之内归还超期图书");
                    dt = borrowBLL.GetBorrow(borrow.rdID);
                    ShowBorrowData();
                }
            }
        }

        private void btnPayBook_Click(object sender, EventArgs e)
        {
            MessageBox.Show("确定您借阅的图书已丢失？");
            //图书丢失，罚款金额为书原本价格
            if (txtrdID.Text == "" || txtbkCode.Text == "" || txtPay.Text == "")
                MessageBox.Show("缴纳罚款请输入读者号和书号！！！");
            else
            {
                int rdID = Convert.ToInt32(txtrdID.Text);
                int bkID = Convert.ToInt32(txtbkCode.Text);
                float IdPunishMoney = Convert.ToSingle(txtPay.Text);
                book = BookAdmin.GetBook(bkID);
                if (book.bkPrice != IdPunishMoney)
                {
                    MessageBox.Show("您缴纳的金额小于赔偿金额，请一次交清完毕！！！");
                    MessageBox.Show("应缴纳金额：" + Convert.ToString(book.bkPrice));
                }
                else
                {
                    borrow = BorrowAdmin.GetAllBorrow(rdID, bkID);//得到借阅记录
                    MessageBox.Show("账号：" + borrow.BorrowID);
                    // BorrowAdmin.DeleteBorrow(borrow);
                    BorrowAdmin.UpdatePay(rdID, bkID, IdPunishMoney);//更新借阅记录
                    BorrowAdmin.UpdateBookByPay(borrow);//更新图书状态—遗失
                    BorrowAdmin.UpdateReaderByLend(borrow);//删除丢失图书
                    MessageBox.Show("您的罚款已缴清，记录已成功更新！！！");
                }
            }
        }
    }
}
